package com.waiting.reference;

import java.lang.ref.*;

/**
 * @Description 强引用、软引用、弱引用、幻象引用
 * @Author bjweitingting
 * @Date 2019/1/29
 **/
public class Main {
    public static void main(String[] args) {
        //引用队列
        ReferenceQueue refQueue = new ReferenceQueue<>();

        User user = new User("测试软引用");
        //创建一个软引用，并注册到引用队列
        SoftReference<User> softReference = new SoftReference<>(user, refQueue);

        User userTwo = new User("测试弱引用");
        WeakReference<User> weakReference = new WeakReference<>(userTwo, refQueue);

        User userThree = new User("测试幻象引用");
        //创建一个幻象引用，并注册到引用队列refQueue
//        PhantomReference<User> phantomReference = new PhantomReference<>(userThree, refQueue);

        //释放强引用
        userThree = null;
        user = null;
        System.gc();

        System.runFinalization();
        try {
//            System.out.println(softReference.get().getName());
//            System.out.println(weakReference.get().getName());
//            System.out.println(phantomReference.get().getName());
            // Remove 是一个阻塞方法，可以指定 timeout，或者选择一直阻塞
            Thread.sleep(10000);

            Reference<Object> ref = refQueue.remove(1000L);
            if (ref != null) {
                // do something
                System.out.println(ref.getClass().getName());
                System.out.println("ref != null");
            } else {
                System.out.println("ref == null");
            }
        } catch (InterruptedException e) {
            // Handle it
        }
    }
}

class User {
    String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
